package cn.lds.j367.dsbank.controller;

import cn.lds.j367.dsbank.common.condition.CustomerCondition;
import cn.lds.j367.dsbank.common.dto.ResultDTO;
import cn.lds.j367.dsbank.common.utils.Pager;
import cn.lds.j367.dsbank.entity.Certificate;
import cn.lds.j367.dsbank.entity.Customer;
import cn.lds.j367.dsbank.entity.ProvinceCityDistrict;
import cn.lds.j367.dsbank.exception.SysException;
import cn.lds.j367.dsbank.service.CertificateService;
import cn.lds.j367.dsbank.service.CustomerService;
import cn.lds.j367.dsbank.service.ProvinceCityDistrictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    private Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CertificateService certificateService;

    @Autowired
    private ProvinceCityDistrictService provinceCityDistrictService;

    @Autowired
    private CustomerService customerService;
    /**
     * 查看全部客户
     * @return
     */
    @RequestMapping("/show_customer")
    public String showCustomer(Model model, CustomerCondition condition, Pager pager){

        log.info("条件信息：{}",condition);

        ResultDTO<List<Customer>> listResultDTO = customerService.selectCustomerByCustomerCondition(condition, pager);

        if (listResultDTO.getCode() == 2000){
            listResultDTO.getObj().forEach(customer -> log.info("客户信息：{}",customer));

        }

        model.addAttribute("customerResult",listResultDTO);

        return "customer/show_customer_all";
    }

    /**
     * 添加客户
     * @return
     */
    @RequestMapping("/add_customer")
    public String addCustomer(Model model){

        List<Certificate> certificates = certificateService.selectCertificateAll();

        List<ProvinceCityDistrict> provinceCityDistricts = provinceCityDistrictService.selectProvinceCityDistrictByParentId(0);

        model.addAttribute("certificates",certificates);

        model.addAttribute("provinces",provinceCityDistricts);


        return "customer/add_customer";
    }
    @RequestMapping("/do_add_customer")
    public String doAddCustomer(MultipartFile upload,@Valid Customer customer, BindingResult errors, HttpServletRequest request) throws SysException, IOException {

        log.info("客户信息：" + customer);

        //后端验证信息，统一异常处理
        if (errors.hasErrors()){
            List<FieldError> fieldErrors = errors.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getField() + ":"+fieldError.getDefaultMessage());
                //获取错误名
                String errorName = fieldError.getField();
                //获取错误信息
                String errorMsg = fieldError.getDefaultMessage();
                //抛出异常
                throw new SysException(fieldError.getField() + ":"+fieldError.getDefaultMessage());
            }
        }

        String path = request.getServletContext().getRealPath("/customer_id_img");

        File file = new File(path);

        if (!file.exists()){
            file.mkdir();
        }

        String originalFilename = upload.getOriginalFilename();

        String fileName = UUID.randomUUID().toString().replace("-","") + "_" + originalFilename;

        upload.transferTo(new File(path,fileName));

        customer.setIdImgUrl("/customer_id_img/" + fileName);

        customer.setCreateEmpId(this.getLoginEmp().getEmpId());

        ResultDTO resultDTO = customerService.addCustomer(customer);


        return "redirect:/customer/show_customer";
    }

    /**
     * 客户审核
     * @return
     */
    @RequestMapping("/under_customer")
    public String underCustomer(){
        return "";
    }


}
